package org.leonos.web.system.controller;

import com.jfinal.core.Controller;
import org.apache.commons.lang.StringUtils;
import org.leonos.core.annotation.Check;
import org.leonos.core.common.Const;
import org.leonos.utils.EncryptUtils;
import org.leonos.utils.ICaptchaRender;
import org.leonos.utils.PageCreator;
import org.leonos.utils.Utils;
import org.leonos.web.system.model.User;

/**
 * 基础控制器
 * @author LeonXiao
 */
public class BaseController extends Controller{

    private static final String loginPage = "/WEB-INF/view/base/login.jsp";
    private static final String mainPage = "/WEB-INF/view/base/main/sys_main.jsp";

    /**
     * 系统登录页面
     */
    public void index() {
        render(loginPage);
    }

    /**
     * 获取图形验证码
     */
    public void getCaptcha() {
        render(new ICaptchaRender());
    }

    /**
     * 登录
     */
    public void login() {
        String username = getPara("signin-user");
        String password = getPara("signin-password");
        String captcha = getPara("signin-captcha");
        String license = getPara("license");

        if (StringUtils.isEmpty(username)) {
            setAttr("msg", "用户名不得为空");
            render(loginPage);
            return;
        }
        if (StringUtils.isEmpty(password)) {
            setAttr("msg", "密码不得为空");
            render(loginPage);
            return;
        }
        if (StringUtils.isEmpty(captcha)) {
            setAttr("msg", "验证码不得为空");
            render(loginPage);
            return;
        }
        if (StringUtils.isEmpty(license)) {
            setAttr("msg", "请同意该协议");
            render(loginPage);
            return;
        }

        boolean validateCaptcha = validateCaptcha("signin-captcha"); // 验证码判定
        if (!validateCaptcha) {
            setAttr("msg", "验证码不正确");
            render(loginPage);
            return;
        }

        String encryptPassword = EncryptUtils.MD5(password); // MD5进行加密处理
        User user = User.dao.findByUsername(username);
        if (Utils.isNull(user)) {
            setAttr("msg", "用户名不存在");
            render(loginPage);
            return;
        }
        user = User.dao.findByUsernameAndPassword(username, encryptPassword);
        if (Utils.isNull(user)) {
            setAttr("msg", "密码不正确");
            render(loginPage);
            return;
        }

        setSessionAttr(Const.LOG_USER, user);
        redirect("/main");
    }

    /**
     * 登出
     */
    public void logout() {
        getSession().invalidate();
        index();
    }

    /**
     * 管理后台主页面
     */
    @Check(isLogin = true)
    public void main() {
        User user = getSessionAttr(Const.LOG_USER);

        if (Utils.isNull(user)) {
            redirect("/index");
            return;
        }

        setAttr("toolMenu", PageCreator.createToolMenuByUser(user));
        render(mainPage);
    }

}
